package TcpDemon02;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemon02 {
    public static void main(String[] args) {
        try(
                // 1. create serverSocket
                ServerSocket serverSocket = new ServerSocket(9000);
                // 2. monitor client connection
                Socket socket=serverSocket.accept();
                // 3. get InputStream
                InputStream is=socket.getInputStream();
                // 4. file write
                FileOutputStream fos=new FileOutputStream(new File("receive.jpg"));
                // 5. notice
                OutputStream os=socket.getOutputStream();
                ){
            //
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
            // 5. notice client that we accept all
            os.write("我接收完毕了，可以断开了。".getBytes());
        }catch(Exception e){
            System.out.println(e);
        }
    }
}
